console.log('server start!');
var apn = require('apn');
var io = require('socket.io').listen(8000);
io.set ('log level', 1);
io.set('heartbeat interval', 30);
io.set('heartbeat timeout', 60);
// io.set('transports', ['xhr-polling']);

var redis = require('redis');
var client = redis.createClient();//'6379', '192.168.1.6'
var subClient = redis.createClient();//'6379', '192.168.1.6'


client.on('error', function (err) {
    console.log('Error ' + err);
});

client.on('connect', function(){
	console.log('client connect!!!')
});

subClient.on('connect', function(){
	console.log('subclient connect!!!')
	subClient.subscribe('messages')
});

subClient.on('message', function(channel, data){
	console.log('新订阅消息：' + data);
	var message = JSON.parse(data);
	if(io.sockets.clients(message.nickname).length > 0) {
		console.log('用户在线，将socket转发！')
		io.sockets.in(message.nickname).emit('notice', message);
	}else{
		console.log('用户不在线，将push！')
		iosPush(message)
	}
});

function iosPush(message){
	client.hget(message.nickname, 'device_token', function(err, replies){
		var device_token =  replies;
		if(replies !== null){
			console.log('该设备系ios，将推送！')
			var options = { 
				"gateway": "gateway.push.apple.com",
				"cert": "cert.pem",
				"key": "key.pem",
				"batchFeedback": true,
				"interval": 300,
				"errorCallback": function(err){
					console.log(err)
				}
			},
			    apnConnection = new apn.Connection(options),
			    device = new apn.Device(device_token),
			    note = new apn.Notification();
				feedback = new apn.Feedback(options);
			feedback.on("feedback", function(devices) {
			    devices.forEach(function(item) {
			        console.log(item.device + item.time);
			    });
			});
			note.expiry = Math.floor(Date.now() / 1000) + 60;
			note.badge = message.unread_messages_count;
			note.alert = "收到" + message.unread_messages_count + "条新消息！";
			note.payload = message;
			apnConnection.pushNotification(note, device);
		}else{
			return
		}
	});
}

io.sockets.on('connection', function(socket) {

	socket.on('join', function(data) {
		socket.join(data.room);
		console.log('\n' + data.room + ': ' + io.sockets.clients(data.room).length);
		console.log('\n' + data.room + ': ' + data.device_token);
		client.hset(data.room, 'device_token', data.device_token||null);
		// client.hgetall(data.room, function(err, replies){
		// 	if (replies !== null) {
		// 		console.log(replies);
		// 		io.sockets.in(data.room).emit('notice', replies);
		// 		// client.del(data.room);
		// 	}
		// });
	});

	socket.on('post', function(data) {
		console.log('\n' + data.from + ' 发了一条消息给 ' + data.to);
		if(io.sockets.clients(data.to).length < 1){
			console.log(data.to + '已离线，将保存该信息至下次发送！');
			client.hset(data.to, data.from, 1, redis.print)
		}else{
			var obj = new Object();
			obj[data.from] = 1;
			io.sockets.in(data.to).emit('notice', obj);

			// ios push
			client.hget(data.to, 'device_token', function(err, replies){
				var device_token =  replies;
				console.log(device_token);
				var options = { 
					"gateway": "gateway.sandbox.push.apple.com",
					"cert": "cert.pem",
					"key": "key.pem",
					"batchFeedback": true,
    				"interval": 300,
    				"errorCallback": function(err){
    					console.log(err)
    				}
				},
				    apnConnection = new apn.Connection(options),
				    device = new apn.Device(device_token),
				    note = new apn.Notification();
				var feedback = new apn.Feedback(options);
				feedback.on("feedback", function(devices) {
				    devices.forEach(function(item) {
				        console.log(item.device + item.time);
				    });
				});
				note.expiry = Math.floor(Date.now() / 1000) + 60;
				note.badge = 3;
				note.alert = "您有一条新消息！";
				note.payload = {'messageFrom': 'Caroline'};
				apnConnection.pushNotification(note, device);
			});
		}
	})

	socket.on('error', function(){
		console.log('error');
	})

});

